import React, { useCallback, useMemo, useRef } from 'react';
import { Alert, Icon, message, Popconfirm, Skeleton, Spin, Table, Tag, Tooltip } from 'antd';
import { useRequest } from '@/hooks';
import {
    fetchEmployeeInfo,
    getEmployeeEntityAllMaterial,
    removeEmployeeEntityMaterial,
    uploadEmployeeEntityMaterial
} from '@/pages/EntryManage/services';
import PropTypes from 'prop-types';
import PreviewModal from '@/pages/EntryManage/components/Preview/PreviewModal';
import { IMG_TYPE, OFFICE_TYPE, PDF_TYPE } from '@/containers/upload/constant';
import IconFont from '@/components/IconFont';
import UploadOss from '@/components/UploadOss';
import { DividerContainer } from '@/molecules';
import authHelper from '@/utils/auth/helper';
import { saveFile } from '@/utils/utils';
import styles from '../index.less';

/**
 * 入职详情 - 入职材料
 */
const EntryMaterialTabContent = ({ employeeCode }) => {
    const { data: canAction } = useRequest(() => fetchEmployeeInfo(employeeCode), {
        cacheKey: `entry-employee-info-${employeeCode}`,
        refreshDeps: [employeeCode],
        ready: !!employeeCode,
        formatResult: res => {
            if (res.code === 10000) {
                return res.data.entryStatus < 100;
            }
            return null;
        }
    });

    // 获取数据
    const materialDataRequest = useRequest(() => getEmployeeEntityAllMaterial({ employeeCode }), {
        cacheKey: `entry-material-${employeeCode}`,
        cacheTime: 3600000,
        refreshDeps: [employeeCode],
        formatResult: res => {
            if (res) {
                const { code, data, msg } = res;
                if (code === 10000) {
                    const { electronMaterials = [], entityMaterials = [] } = data;
                    return [
                        ...electronMaterials.map(item => ({
                            name: item.materialName,
                            code: item.materialCode,
                            status: item.resourceStatus,
                            type: item.resourceType,
                            value: item.materialValue,
                            uploadCountLimit: item.uploadCountLimit,
                            uploadFormatLimit: item.uploadFormatLimit,
                            uploadFormatTip: item.uploadFormatTip,
                            uploadTip: item.uploadTip
                        })),
                        ...entityMaterials.map(item => ({
                            name: item.categoryName,
                            code: item.categoryCode,
                            status: item.resourceStatus,
                            type: item.resourceType,
                            isSingle: item.isSingle,
                            urlList: item.urlList,
                            uploadCountLimit: item.uploadCountLimit,
                            uploadFormatLimit: item.uploadFormatLimit,
                            uploadFormatTip: item.uploadFormatTip,
                            uploadTip: item.uploadTip
                        }))
                    ];
                }
                message.error(msg);
            }
            return undefined;
        }
    });

    // 上传材料
    const uploadMaterialRequest = useRequest(param => uploadEmployeeEntityMaterial(param), {
        manual: true,
        onSuccess: result => {
            const { code, msg } = result;
            if (code === 10000) {
                materialDataRequest.refresh();
                message.success('上传成功');
            } else {
                message.error(msg);
            }
        }
    });

    // 删除材料
    const removeMaterialRequest = useRequest(param => removeEmployeeEntityMaterial(param), {
        manual: true,
        onSuccess: result => {
            const { code, msg } = result;
            if (code === 10000) {
                materialDataRequest.refresh();
                message.success('删除成功');
            } else {
                message.error(msg);
            }
        }
    });

    const previewModalRef = useRef();

    // 预览附件
    const handlePreview = file => {
        const fileType = file.originName
            .split('.')
            .pop()
            .toLowerCase();
        if (IMG_TYPE?.includes(fileType)) {
            previewModalRef.current.open({
                type: 'image',
                origin: file.url
            });
        } else if (PDF_TYPE?.includes(fileType)) {
            previewModalRef.current.open({
                type: 'pdf',
                title: file.keyName,
                origin: file.url
            });
        } else if (OFFICE_TYPE?.includes(fileType)) {
            previewModalRef.current.open({
                type: 'office',
                title: file.keyName,
                origin: file.url,
                encode: true
            });
        }
    };

    // 下载附件
    const handleDownload = useCallback(urlList => {
        urlList.forEach(item => {
            saveFile(item.url, item.originName);
        });
    }, []);

    // 入职材料表格
    const columns = useMemo(
        () => [
            {
                title: '名称',
                dataIndex: 'name'
            },
            {
                title: '类型',
                width: '100px',
                dataIndex: 'type',
                render: (text, record) => ({ electronMaterial: '电子材料', entityMaterial: '纸质材料' }[record.type])
            },
            {
                title: '状态',
                width: '100px',
                dataIndex: 'status',
                render: text => {
                    if (text === 1) {
                        return <Tag color="green">已提供</Tag>;
                    }
                    if (text === 0) {
                        return <Tag>未提供</Tag>;
                    }
                    return null;
                }
            },
            {
                title: '材料',
                className: 'fileColumn',
                render: (files, record) => {
                    if (record.urlList && record.urlList.length) {
                        const showDelete =
                            canAction && authHelper.checkCode('office:personnel:progress:entry:detail:material:del');
                        const showPreview = authHelper.checkCode('office:personnel:progress:entry:detail:material:get');
                        return (
                            <div className={styles.filesWrapper}>
                                {record.urlList.map(file => (
                                    <div key={file.keyName} className="file">
                                        <Tooltip placement="top" title={file.originName}>
                                            <span className="fileName">{file.originName}</span>
                                        </Tooltip>
                                        {showPreview && file.url && (
                                            <span className="preview">
                                                <a onClick={() => handlePreview(file)}>
                                                    <Icon type="eye" />
                                                </a>
                                            </span>
                                        )}
                                        {showDelete && (
                                            <Popconfirm
                                                placement="top"
                                                title="是否删除文件"
                                                onConfirm={() => {
                                                    removeMaterialRequest.run({
                                                        categoryCode: record.code,
                                                        employeeCode,
                                                        keyName: file.keyName
                                                    });
                                                }}
                                                okText="是"
                                                cancelText="否"
                                            >
                                                <a className="preview">
                                                    <IconFont icon="iconshanchu" />
                                                </a>
                                            </Popconfirm>
                                        )}
                                    </div>
                                ))}
                            </div>
                        );
                    }
                    if (record.value) {
                        return (
                            <div className="materialList" title={record.value}>
                                {record.value}
                            </div>
                        );
                    }
                    return <div className="noFile">未上传</div>;
                }
            },
            {
                title: '操作',
                dataIndex: 'active',
                width: 100,
                render: (text, record) => {
                    const { uploadCountLimit = 0, uploadFormatLimit, uploadFormatTip, urlList, code, type } = record;
                    const showUploader =
                        canAction &&
                        authHelper.checkCode('office:personnel:progress:entry:detail:material:upload') &&
                        (!uploadCountLimit ? false : urlList.length < uploadCountLimit);
                    const showDownload =
                        authHelper.checkCode('office:personnel:progress:entry:detail:material:download') &&
                        !!urlList?.length;
                    return (
                        type === 'entityMaterial' && (
                            <DividerContainer>
                                {showUploader && (
                                    <UploadOss
                                        uploadUrl="/api/resource/public/oss/producePutPreSignUrls"
                                        dragAble={false}
                                        checkFileSize={10}
                                        checkFileSizeMsg="文件大小不可超过10M，请重新选择"
                                        categoryCode={code}
                                        sysCode="OA"
                                        businessCode="SysAvatar"
                                        isSingle
                                        showPreviewFile
                                        checkFileType={uploadFormatLimit}
                                        checkFileTypeMsg={uploadFormatTip}
                                        onUploaded={async (file = []) => {
                                            try {
                                                await uploadMaterialRequest.run({
                                                    employeeCode,
                                                    materials: [
                                                        {
                                                            categoryCode: code,
                                                            keyNameAndOpt: [`ADD:${file[0]?.keyName}`]
                                                        }
                                                    ]
                                                });
                                            } catch (error) {
                                                message.error(error.message);
                                            }
                                        }}
                                    >
                                        <Icon type="upload" className={styles.uploadButton} />
                                    </UploadOss>
                                )}
                                {showDownload && (
                                    <Icon
                                        type="download"
                                        className={styles.uploadButton}
                                        onClick={() => handleDownload(urlList)}
                                    />
                                )}
                            </DividerContainer>
                        )
                    );
                }
            }
        ],
        [canAction, employeeCode, handleDownload, removeMaterialRequest, uploadMaterialRequest]
    );

    // 错误处理
    if (materialDataRequest?.error) {
        return <Alert type="error" message={materialDataRequest.error} />;
    }

    // render
    return (
        <Skeleton loading={!materialDataRequest?.data && materialDataRequest?.loading}>
            <Spin spinning={materialDataRequest?.data && materialDataRequest?.loading}>
                <div className="entryMaterialTableWrap">
                    <Table
                        className={styles.paperMaterialsTable}
                        rowKey="code"
                        bordered
                        columns={columns}
                        dataSource={materialDataRequest?.data}
                        pagination={false}
                    />
                    <PreviewModal height="650px" ref={previewModalRef} />
                </div>
            </Spin>
        </Skeleton>
    );
};

// prop
EntryMaterialTabContent.propTypes = {
    employeeCode: PropTypes.string.isRequired
};

EntryMaterialTabContent.displayName = 'EntryMaterialTabContent';

export default EntryMaterialTabContent;
